﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Strom.Core.Network;
using Strom.Core.Network.Packets;

namespace Strom.Client.Network
{
    public static class Parser
    {
        static readonly Dictionary<byte, IPacket> RegisteredPackets = new Dictionary<byte, IPacket>();

        public static void RegisterNewClientOnParser(BaseClient client)
        {
            client.ClientDisconnected += client_ClientDisconnected;
            client.PacketReceived += client_PacketReceived;
        }

        static void client_ClientDisconnected(BaseClient client)
        {
            client.PacketReceived -= client_PacketReceived;
            client.ClientDisconnected -= client_ClientDisconnected;
        }

        static void client_PacketReceived(BaseClient client, Packet packet)
        {
            if (!RegisteredPackets.ContainsKey(packet.ID))
                return;

            RegisteredPackets[packet.ID].Unpack(client, packet);
        }

        public static void RegisterPackets()
        {
            RegisteredPackets.Add(LoginRequestPacket.ID, new LoginRequestPacket());
            RegisteredPackets.Add(LoginRequestResponse.ID, new LoginRequestResponse(ClientManager.GUI.Login));
            RegisteredPackets.Add(CharactersListPacket.ID, new CharactersListPacket(ClientManager.GUI.Login));
            RegisteredPackets.Add(CreateCharacterRequestPacket.ID, new CreateCharacterRequestPacket());
            RegisteredPackets.Add(CreateCharacterRequestResponsePacket.ID, new CreateCharacterRequestResponsePacket());
        }

        public static void SetCreateCharacterForm(GUI.FormCreateCharacter formCreateCharacter)
        {
            RegisteredPackets[CreateCharacterRequestResponsePacket.ID] = new CreateCharacterRequestResponsePacket(formCreateCharacter);
        }
    }
}
